﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace DevCore.Utility
{
    /// <summary>
    /// Json数据辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary> 
        /// DataTable转为json 
        /// </summary> 
        /// <param name="dt">DataTable</param> 
        /// <returns>json数据</returns> 
        public static string DtToJson(DataTable dt)
        {
            StringBuilder sbValue = new StringBuilder();
            String strRow = "";
            for (int index = 0; index < dt.Rows.Count; index++)
            {
                DataRow dr = dt.Rows[index];
                strRow = "{";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    DataColumn dc = dt.Columns[i];
                    if (i == dt.Columns.Count - 1)
                    {
                        strRow = strRow + "\"" + dc.ColumnName + "\":\"" + StringHelper.ObjectToStr(dr[dc.ColumnName]) + "\"";
                    }
                    else
                    {
                        strRow = strRow + "\"" + dc.ColumnName + "\":\"" + StringHelper.ObjectToStr(dr[dc.ColumnName]) + "\",";
                    }
                }
                if (index == dt.Rows.Count - 1)
                {
                    strRow = strRow + "}";
                }
                else
                {
                    strRow = strRow + "},";
                }

                sbValue.Append(strRow);
            }

            return sbValue.ToString();

        }

        /// <summary>
        /// DataTable转换为EasyUi DataGrid json数据
        /// </summary>
        /// <param name="dtInfo">当前数据集值</param>
        /// <param name="recordCount">当前符合条件的总记录数</param>
        /// <returns></returns>
        public static String DtToEasyUIDataGridJson(DataTable dtInfo, long recordCount)
        {
            String rValue = String.Empty;
            String tmpStr = JsonHelper.DtToJson(dtInfo);
            rValue = "{\"total\":\"" + recordCount + "\",\"rows\":[" + tmpStr + "]}";
            return rValue;
        }
    }
}